<template>
  <div class="pdf-viewer">
    <div v-if="loading" class="loading">
      <div class="spinner"></div>
      <p>正在加载PDF文档... {{ progress }}%</p>
    </div>

    <div v-else-if="error" class="error">
      <i class="fas fa-exclamation-circle"></i>
      <p>加载PDF时出错: {{ error }}</p>
    </div>

    <div v-else-if="numPages">
      <pdf
        :src="pdfSrc"
        :page="currentPage"
        :scale="scale"
        :rotate="rotate"
        @progress="onProgress"
        @error="onError"
        @num-pages="numPages = $event"
        @link-clicked="onLinkClicked">
      </pdf>
    </div>

    <div v-else class="status">
      <p>请输入PDF URL并点击加载</p>
    </div>
  </div>
</template>

<script>
import pdf from 'pdfvuer'

export default {
  components: { pdf },
  props: {
    src: String,
    currentPage: Number,
    scale: Number,
    rotate: Number
  },
  data() {
    return {
      pdfSrc: null,
      numPages: 0,
      loading: false,
      error: null,
      progress: 0
    }
  },
  methods: {
    loadPdf() {
      if (!this.src) {
        this.error = "PDF源未指定";
        return;
      }
      
      this.loading = true;
      this.error = null;
      this.numPages = 0;
      this.progress = 0;
      
      this.pdfSrc = pdf.createLoadingTask(this.src);
      
      this.pdfSrc.then(pdf => {
        this.numPages = pdf.numPages;
        this.loading = false;
        this.$emit('loaded', pdf);
      }).catch(error => {
        this.error = error.message;
        this.loading = false;
        this.$emit('error', error);
      });
    },
    onProgress(progress) {
      this.progress = Math.round(progress * 100);
      this.$emit('progress', progress);
    },
    onError(error) {
      this.error = error;
      this.loading = false;
      this.$emit('error', error);
    },
    onLinkClicked(page) {
      this.$emit('link-clicked', page);
    }
  },
  watch: {
    src() {
      this.loadPdf();
    }
  },
  mounted() {
    if (this.src) {
      this.loadPdf();
    }
  }
}
</script>